/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.ues21.tcs.ecommerce2011.mvc.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author vascordoba
 */
public class SessionFilter implements Filter {

    public SessionFilter() {
        
    } 

    private List<String> urlList;

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String url = req.getServletPath();
        boolean allowedRequest = false;
        if(urlList.contains(url)) {
            allowedRequest = true;
        }

        HttpSession session = req.getSession(false);
        if (!allowedRequest) {
            if (session==null || (session.getAttribute("usuario")==null && session.getAttribute("administrador")==null)) {
                req.getRequestDispatcher("index.jsp?errorMsg=No esta autorizado a acceder al recurso solicitado ("+url+")").forward(req, resp);
            }
            else{
                chain.doFilter(req, resp);
            }
        }
        else{
            if(url.equals("/login.do") && (
                    req.getParameter("user")==null ||
                    req.getParameter("pass")==null)){
                req.getRequestDispatcher("index.jsp?errorMsg=No esta autorizado a acceder al recurso solicitado ("+url+")").forward(req, resp);
            }
            else{
                chain.doFilter(req, resp);
            }
        }
    }
    
    /**
     * Destroy method for this filter 
     */
    @Override
    public void destroy() { 
    }

    @Override
    public void init(FilterConfig fc) throws ServletException {
        urlList=new ArrayList<String>();
        urlList.add("/");
        urlList.add("/index.jsp");
        urlList.add("/login.do");
        urlList.add("/logOut.do");
        urlList.add("/view/error/ErrorLogin.jsp");
    }


}
